package com.example.stu.jinrong;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    private WebView webView;
    private TextView title;
    private boolean loadingFinished = true;
    private boolean redirect = false;
    private RelativeLayout back;
    private ProgressBar progressBar;
    private String url = "http://niwotago.vip/";
    private String TAG = "测试";
    private DownloadManager dm;
    private long enqueue;
    //    private CustomDialog dialog;
//    private String download = "http://apk.count321.cn/1541744082418.apk";
    private LocalBroadcastManager mLocalBroadcastManager;
    public static final String BROADCAST_ACTION =
            "com.example.android.threadsample.BROADCAST";
    public static final String EXTENDED_DATA_STATUS =
            "com.example.android.threadsample.STATUS";
    private boolean isRegisterReceiver;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = findViewById(R.id.web_view);
        back = findViewById(R.id.follow_re_back);
        title = findViewById(R.id.toolbar_title);
        progressBar = findViewById(R.id.progress);

//        dialog = new CustomDialog(this, "加载中");
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (webView.canGoBack()) {
                    webView.goBack();
                    return;
                }
                finish();
            }
        });
        loadWeb();
    }

    public void loadWeb() {

        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String s1, String s2, String s3, long l) {
                Log.i(TAG, "onDownloadStart: url== " + url);
                startDownload(url);
                Log.i(TAG, "onDownloadStart: " + Thread.currentThread().getName());
            }

        });
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

        //支持弹窗，也就是支持html网页弹框
        webView.setWebChromeClient(new WebChromeClient() {
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }

            public void onProgressChanged(WebView view, int newProgress) {
                //显示进度条
                Log.i(TAG, "onProgressChanged: " + Thread.currentThread().getName());
                progressBar.setProgress(view.getProgress());
                progressBar.setVisibility(view.getProgress() == 100 ? View.GONE : View.VISIBLE);
                super.onProgressChanged(view, newProgress);
            }

        });

        //支持html中javascript解析，不管是不是js和android交互，只要网页中含有js都要
        webView.getSettings().setJavaScriptEnabled(true);
        //此方法可以在webview中打开链接而不会跳转到外部浏览器

        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
                if (!loadingFinished) {
                    redirect = true;
                }
                loadingFinished = false;
//                urlNewString = download;

                view.loadUrl(urlNewString);
                Log.e(TAG, "shouldOverrideUrlLoading: " + urlNewString);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap facIcon) {
                loadingFinished = false;
//                dialog.show();
            }

            @Override
            public void onPageFinished(WebView view, String url) {

                if (!redirect) {
                    loadingFinished = true;
                }

                if (loadingFinished && !redirect) {
                    //HIDE LOADING IT HAS FINISHED
                    if (webView.canGoBack()) {
                        title.setText(webView.getTitle());
                    } else {
                        title.setText(getResources().getString(R.string.app_name));
                    }
                } else {
                    redirect = false;
                }

            }
        });
        webView.loadUrl(url);
    }

    private void startDownload(String url) {
        Log.i(TAG, "startDownload: 开始下载" + url);

        dm = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(
                Uri.parse(url));
        String fileName = url.substring(url.lastIndexOf("/") + 1);
        request.setMimeType("application/vnd.android.package-archive");
        request.setVisibleInDownloadsUi(true);

        request.setDescription("下载完后请点击打开");
        request.setDestinationInExternalFilesDir(this,
                Environment.DIRECTORY_DOWNLOADS + File.separator + "appCenter", fileName);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        enqueue = dm.enqueue(request);
        Intent localIntent = new Intent(BROADCAST_ACTION);

        localIntent.putExtra(EXTENDED_DATA_STATUS, enqueue);
        //查询下载信息
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(enqueue);
        try {
            boolean isGoging = true;
            while (isGoging) {
                Cursor cursor = dm.query(query);
                if (cursor != null && cursor.moveToFirst()) {
                    int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                    switch (status) {
                        //如果下载状态为成功
                        case DownloadManager.STATUS_SUCCESSFUL:
                            isGoging = false;
                            installAPK();
                            break;
                    }
                }

                if (cursor != null) {
                    cursor.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void installAPK() {

        Intent intent = new Intent();
        File apkFile = queryDownloadedApk();
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//7.0启动姿势<pre name="code" class="html">    //com.xxx.xxx.fileprovider为上述manifest中provider所配置相同；apkFile为问题1中的外部存储apk文件</pre>
            uri = FileProvider.getUriForFile(this, "com.example.stu.jinrong", apkFile);
            intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//7.0以后，系统要求授予临时uri读取权限，安装完毕以后，系统会自动收回权限，次过程没有用户交互
        } else {//7.0以下启动姿势
            uri = Uri.fromFile(apkFile);
            intent.setAction(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        startActivity(intent);
    }

    public File queryDownloadedApk() {
        File targetApkFile = null;
        if (enqueue != -1) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(enqueue);
            query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
            Cursor cur = dm.query(query);
            if (cur != null) {
                if (cur.moveToFirst()) {
                    String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    if (!uriString.isEmpty()) {
                        targetApkFile = new File(Uri.parse(uriString).getPath());
                    }
                }
                cur.close();
            }
        }
        return targetApkFile;
    }


    public void clearCurrentTask(long downloadId) {
        DownloadManager dm = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
        try {
            dm.remove(downloadId);
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        }
    }

    private void setReceiver() {
        if (!isRegisterReceiver) {
            DownLoadCompleteReceiver receiver = new DownLoadCompleteReceiver();
            IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
            this.registerReceiver(receiver, intentFilter);
            isRegisterReceiver = true;
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webView.removeAllViews();
        webView.destroy();
    }
}
